package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentBusinessTenderChildBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MemberBiddingEntity;
import com.sgb.member.entity.MemberBiddingPreEntity;
import com.sgb.member.entity.MemberTenderBean;
import com.sgb.member.entity.MemberTenderListEntity;
import com.sgb.member.ui.activity.MemberBusinessActivity;
import com.sgb.member.ui.adapter.HomeOtherMemberAdapter;
import com.sgb.member.util.TenderUtil;
import com.sgb.member.view_model.BusinessTenderModel;
import com.sgb.member.weight.SimpleResult;
import com.sgb.member.weight.TenderTypeOtherPopup;
import com.sgb.member.weight.TenderTypePopup;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

// 会员招采经营_招标报名
public class BusinessTenderFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener, XChooseDialog.DialogCallBackImpl {

    public static BusinessTenderFragment newInstance(int position, CommonPopEntity entity) {
        BusinessTenderFragment fragment = new BusinessTenderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putSerializable("ENTITY", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Inject
    public BusinessTenderModel sModel;
    private FragmentBusinessTenderChildBinding mBinding;


    private int mCurTenderPos; // 主页面TAB下标
    // 经营地址Popup
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;

    private String mNo1 = ""; // "招标类型");
    private String mNo2 = ""; // "");
    private String mNo3 = ""; // "招标状态");
    private String mNo4 = ""; // "招标方式");
    private String mNo5 = ""; // "报名开始时间")
    private String mNo51 = ""; // "报名截至时间")
    private String mNo6 = ""; // "概算金额");
    private String mNo7 = ""; // "发布时间")
    private String mNo8 = ""; // "省份");
    private String mNo9 = ""; // "市区");
    private String mNoSort = ""; // 综合排序
    private String member_level = "";//会员等级

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_business_tender_child, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        assert getArguments() != null;
        mCurTenderPos = getArguments().getInt("INDEX", 0);
        mBinding.chooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mNameArray.size(); i++) {
                    XChooseEntity chooseEntity = mData.get(mData.keyAt(i));
                    if (chooseEntity != null) {
                        if (chooseEntity.getList() == null || chooseEntity.getList().size() == 0) {
                            int sort = chooseEntity.getSort();
                            switch (mCurTenderPos) {
                                case 0:
                                    if (sort == PickCateType.TYPE_1 || sort == PickCateType.TYPE_8) {
                                        loadOtherData();
                                        return;
                                    }
                                    break;
                                case 1:
                                    // 会员招采经营_招标预告
                                    if (sort == PickCateType.TYPE_1 || sort == PickCateType.TYPE_3 || sort == PickCateType.TYPE_4 || sort == PickCateType.TYPE_51 || sort == PickCateType.TYPE_6 || sort == PickCateType.TYPE_8) {
                                        loadOtherData();
                                        return;
                                    }
                                    break;
                                case 2:
                                    // 会员招采经营_竞价采购
                                    if (sort == PickCateType.TYPE_1 || sort == PickCateType.TYPE_6 || sort == PickCateType.TYPE_7 || sort == PickCateType.TYPE_8) {
                                        loadOtherData();
                                        return;
                                    }
                                    break;
                                case 3:
                                    // 会员招采经营_招标预告
                                    if (sort == PickCateType.TYPE_1 || sort == PickCateType.TYPE_4 || sort == PickCateType.TYPE_5 || sort == PickCateType.TYPE_6 || sort == PickCateType.TYPE_8) {
                                        loadOtherData();
                                        return;
                                    }
                                    break;
                            }
                        }
                    }
                }
                mData.get(PickCateType.TYPE_1).setHide(true);
                mChooseDialog.initData(mData, mFilters);
                mChooseDialog.showDialog();
            }
        });

        initTopRecycler();
        initChooseDialog();
        initPopup();
        initRecycler();
    }

    @Override
    protected void onLazyLoad() {
        // 招标类型
        sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_1, "", false);
        loadData(false);
    }

    public void loadData(boolean isLoadMore) {
        String text = "";
        try {
            text = ((MemberBusinessActivity) getActivity()).getSearchText();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            text = "";
        }
        sModel.tenderBidderList(mCurTenderPos, isLoadMore, text, mNo1, mNo2, mNo3, mNo4, mNo5, mNo51, mNo6, mNo7, mNo8, mNo9, mNoSort, member_level);
    }

    private void loadOtherData() {
        if (isListEmpty(PickCateType.TYPE_1)) {
            sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_1, "", false); // 招标类型
        }
        switch (mCurTenderPos) {
            case 0:
                break;
            case 1:
                // 会员招采经营_招标预告
                if (isListEmpty(PickCateType.TYPE_3)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_3, "", false); // 招标状态
                }
                if (isListEmpty(PickCateType.TYPE_4)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_4, "", false); // 招标方式
                }
                if (isListEmpty(PickCateType.TYPE_51)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_51, "", false); // 报名截至时间
                }
                if (isListEmpty(PickCateType.TYPE_6)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_6, "", false); // 概算金额
                }
                if (isListEmpty(PickCateType.TYPE_10)) {
                    sModel.getMemberLevelData(); // 会员级别
                }
                break;
            case 2:
                // 会员招采经营_竞价采购
                if (isListEmpty(PickCateType.TYPE_7)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_7, "", false); // 发布时间
                }
                if (isListEmpty(PickCateType.TYPE_6)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_6, "", false); // 概算金额
                }
                if (isListEmpty(PickCateType.TYPE_10)) {
                    sModel.getMemberLevelData(); // 会员级别
                }
                break;
            case 3:
                // 会员招采经营_招标预告
                if (isListEmpty(PickCateType.TYPE_4)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_4, "", false); // 招标方式
                }
                if (isListEmpty(PickCateType.TYPE_5)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_5, "", false); // 报名开始时间列表
                }
                if (isListEmpty(PickCateType.TYPE_6)) {
                    sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_6, "", false); // 概算金额
                }
                if (isListEmpty(PickCateType.TYPE_10)) {
                    sModel.getMemberLevelData(); // 会员级别
                }
                break;
        }
        if (scrData == null || scrData.size() == 0) {
            sModel.getAddressModel(PickCateType.TYPE_8);  // 经营地址
        }
    }

    // 更新本地筛选数据
    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_1: // 分类1
                updateTenderTypes(data);
                break;
            case PickCateType.TYPE_2: // 分类2
                updateTenderTypes2(data, 0);
                break;
            case PickCateType.TYPE_3: // 招标状态
                mBinding.popStatus.setData(data, mNo3);
                break;
            case PickCateType.TYPE_4: // 招标方式
                mBinding.popMode.setData(data, mNo3);
                break;
            case PickCateType.TYPE_5: // 报名开始时间列表
                break;
            case PickCateType.TYPE_6: // 招标概算金额
                mBinding.popMoney.setData(data, mNo6);
                break;
            case PickCateType.TYPE_7: // 发布时间
                break;
            case PickCateType.TYPE_8: // 经营地址
                break;

        }
    }

    private List<CommonPopEntity> list;

    public void setMemberLevelData(List<CommonPopEntity> list) {
        this.list = list;
        addMainEntity(PickCateType.TYPE_10, list);
    }

    // 更新顶部一级分类数据
    private void updateTenderTypes(List<CommonPopEntity> data) {
        mBinding.otherType.setVisibility(View.GONE);
        mBinding.tabType1.setVisibility(View.GONE);
        if (data == null || data.size() == 0) {
            showEmpty();
            return;
        }
        mBinding.tabType1.setVisibility(View.VISIBLE);
        TenderUtil.tenderType1(mBinding.tabType1, data, new SimpleResult<CommonPopEntity>() {
            @Override
            public void onResult(CommonPopEntity entity, Object... objects) {
                if (isTabOneDialogRefresh) return;
                int position = (int) objects[0];
                int category = !TextUtils.isEmpty(entity.getNo()) ? Integer.parseInt(entity.getNo()) : 0;
                mCateTitle = CopyUtils.getCateTitle(1, category);
                // 更新一级数据
                refreshItemValue(PickCateType.TYPE_1, position, false);
                // 类别删选 置灰 并隐藏
                mBinding.otherType.refreshChoose(mNo2, "类别", 0);
                mBinding.otherType.setVisibility(View.GONE);
                mBinding.tabType2Layout.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
                // 更新二级数据置空
                for (Integer integer : mCateOther) {
                    refreshItemValue(integer, 0, false);
                }
                // 获取二级数据
                loadTenderSecondType(entity, position, false);
                loadData(false);
            }
        });
        // 初始化加载数据
        loadData(false);
    }

    // 更新顶部二级分类数据
    private void updateTenderTypes2(List<CommonPopEntity> data, int index) {
        if (data == null || data.size() == 0) {
            mBinding.tabType2Layout.setVisibility(View.GONE);
            return;
        }
        mBinding.tabType2Layout.setVisibility(View.VISIBLE);
        TenderUtil.tenderType2(mBinding.tabType2, data, new SimpleResult<CommonPopEntity>() {
            @Override
            public void onResult(CommonPopEntity entity, Object... objects) {
                if (isTabTwoDialogRefresh) return;
                int position = (int) objects[0];
                // 更新二级数据
                for (Integer integer : mCateOther) {
                    refreshItemValue(integer, 0, false);
                }
                refreshItemValue(PickCateType.TYPE_2, position, false);
                mBinding.otherType.refreshChoose(mNo2, "类别", 0);
                if (position == 0 || (entity.getChildren() == null || entity.getChildren().size() == 0)) {
                    mBinding.otherType.setVisibility(View.GONE);
                } else {
                    // 获取三级数据
                    loadTenderOtherType(PickCateType.TYPE_2, entity, position, false);
                    mBinding.otherType.setVisibility(View.VISIBLE);
                }
                loadData(false);
            }
        });
        if (index > 0) {
            mBinding.otherType.setVisibility(View.VISIBLE);
        } else {
            mBinding.otherType.setVisibility(View.GONE);
        }
        if (index > 0) {
            mBinding.tabType2.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Objects.requireNonNull(mBinding.tabType2.getTabAt(index)).select();
                    isTabTwoDialogRefresh = false;
                }
            }, 10);
        }
    }

    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            if (TextUtils.isEmpty(mNo8)) {
                mAddressPop.setData(data, true);
            } else {
                mAddressPop.setDataAndPosition(data, mNo8, mNo9, "", true, true);
            }
        } else {
            sModel.getAddressModel(PickCateType.TYPE_8);
        }
    }


    /**
     * -------------------------------------initRecycler------------------------------------------
     */

    private String[] mCateTitle;

    private void initTopRecycler() {
        // 顶部二级Popup
        mBinding.surveyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getContext() == null) return;
                List<CommonPopEntity> list = mData.get(PickCateType.TYPE_2).getList();
                new XPopup.Builder(getContext())
                        .atView(mBinding.surveyLayout)
                        .popupAnimation(PopupAnimation.NoAnimation)
                        .offsetY(2)
                        .asCustom(new TenderTypePopup(getContext(), list, mBinding.tabType2.getSelectedTabPosition(), new SimpleResult<CommonPopEntity>() {
                            @Override
                            public void onResult(CommonPopEntity entity, Object... objects) {
                                int position = (Integer) objects[0];
                                Objects.requireNonNull(mBinding.tabType2.getTabAt(position)).select();
                                // 更新二级数据
                                for (Integer integer : mCateOther) {
                                    refreshItemValue(integer, 0, false);
                                }
                                refreshItemValue(PickCateType.TYPE_2, position, false);
                                mBinding.otherType.refreshChoose(mNo2, "类别", 0);
                                if (position == 0 || (entity.getChildren() == null || entity.getChildren().size() == 0)) {
                                    mBinding.otherType.setVisibility(View.GONE);
                                } else {
                                    // 获取三级数据
                                    loadTenderOtherType(PickCateType.TYPE_2, entity, position, false);
                                    mBinding.otherType.setVisibility(View.VISIBLE);
                                }
                                loadData(false);
                            }
                        })).show();
            }
        });
    }

    private void initRecycler() {
        TextView textView = mBinding.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        initBaseRecyclerAdapter();
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        switch (mCurTenderPos) {
            case 0: // 全部
                mAdapter.clearDatas();
                break;
            case 1: // 招标公告
                mAdapterBidder.clearDatas();
                break;
            case 2: // 直接竞价
                mAdapterBid.clearDatas();
                break;
            case 3: // 招标预告
                mAdapterPre.clearDatas();
                break;
        }
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    private HomeOtherMemberAdapter<MemberTenderBean> mAdapter; // 全部
    private HomeOtherMemberAdapter<MemberTenderListEntity> mAdapterBidder; // 招标公告
    private HomeOtherMemberAdapter<MemberBiddingPreEntity> mAdapterPre; // 招标预告
    private HomeOtherMemberAdapter<MemberBiddingEntity> mAdapterBid; // 直接竞价

    private void initBaseRecyclerAdapter() {
        mBinding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getResources().getDimension(R.dimen.dp1)));
        switch (mCurTenderPos) {
            case 0: // 全部
                mAdapter = new HomeOtherMemberAdapter<>(getActivity(), R.layout.item_other_tender, null);
                mAdapter.setOnItemClick(new AdapterOnItemClick<MemberTenderBean>() {
                    @Override
                    public void onItemClick(MemberTenderBean memberTenderBean, int position) {
                        sModel.tenderItemClick(memberTenderBean);
                    }
                });
                mAdapter.onIChildClick(new HomeOtherMemberAdapter.IChildClick<MemberTenderBean>() {
                    @Override
                    public void onClick(MemberTenderBean memberTenderBean) {
                        sModel.tenderItemClick(memberTenderBean);
                    }
                });
                mBinding.recyclerView.setAdapter(mAdapter);
                break;
            case 1: // 招标公告
                mAdapterBidder = new HomeOtherMemberAdapter<>(getActivity(), R.layout.item_other_biding, null);
                mAdapterBidder.setOnItemClick(new AdapterOnItemClick<MemberTenderListEntity>() {
                    @Override
                    public void onItemClick(MemberTenderListEntity memberTenderBean, int position) {
                        MemberConfig.getInstance().startTenderDetails(getActivity(), memberTenderBean.getId(), 0);
                    }
                });
                mAdapterBidder.onIChildClick(new HomeOtherMemberAdapter.IChildClick<MemberTenderListEntity>() {
                    @Override
                    public void onClick(MemberTenderListEntity memberTenderBean) {
                        MemberConfig.getInstance().startTenderDetails(getActivity(), memberTenderBean.getId(), 0);
                    }
                });
                mBinding.recyclerView.setAdapter(mAdapterBidder);
                break;
            case 2: // 直接竞价
                mAdapterBid = new HomeOtherMemberAdapter<>(getActivity(), R.layout.item_other_bidding2, null);
                mAdapterBid.setOnItemClick(new AdapterOnItemClick<MemberBiddingEntity>() {
                    @Override
                    public void onItemClick(MemberBiddingEntity biddingEntity, int position) {
                        sModel.getUrlSetting("competitivePurchase", null, biddingEntity.getId());
                    }
                });
                mAdapterBid.onIChildClick(new HomeOtherMemberAdapter.IChildClick<MemberBiddingEntity>() {
                    @Override
                    public void onClick(MemberBiddingEntity tenderListEntity) {
                        sModel.getUrlSetting("competitivePurchase", null, tenderListEntity.getId());
                    }
                });
                mBinding.recyclerView.setAdapter(mAdapterBid);
                break;
            case 3: // 招标预告
                mAdapterPre = new HomeOtherMemberAdapter<>(getActivity(), R.layout.item_other_bidding_pre, null);
                mAdapterPre.setOnItemClick(new AdapterOnItemClick<MemberBiddingPreEntity>() {
                    @Override
                    public void onItemClick(MemberBiddingPreEntity preNoticeItemEntity, int position) {
                        if (preNoticeItemEntity.getTenderState() == 8) {
                            MemberConfig.getInstance().startPickNoticeDetail(getActivity(), preNoticeItemEntity.getTenderNo() + "");
                        } else {
                            MemberConfig.getInstance().startTenderDetails(getActivity(), preNoticeItemEntity.getTenderNo() + "", 0);
                        }
                    }
                });
                mAdapterPre.onIChildClick(new HomeOtherMemberAdapter.IChildClick<MemberBiddingPreEntity>() {
                    @Override
                    public void onClick(MemberBiddingPreEntity preNoticeItemEntity) {
                        if (preNoticeItemEntity.getTenderState() == 8) {
                            MemberConfig.getInstance().startPickNoticeDetail(getActivity(), preNoticeItemEntity.getTenderNo() + "");
                        } else {
                            MemberConfig.getInstance().startTenderDetails(getActivity(), preNoticeItemEntity.getTenderNo() + "", 0);
                        }
                    }
                });
                mBinding.recyclerView.setAdapter(mAdapterPre);
                break;
        }
    }

    public <T> void refreshRecycler(List<T> list, boolean isLoadMore, boolean noMoreData) {
        switch (mCurTenderPos) {
            case 0: // 全部
                refreshRecyclerBase(mAdapter, list, isLoadMore, noMoreData);
                break;
            case 1: // 招标公告
                refreshRecyclerBase(mAdapterBidder, list, isLoadMore, noMoreData);
                break;
            case 2: // 直接竞价
                refreshRecyclerBase(mAdapterBid, list, isLoadMore, noMoreData);
                break;
            case 3: // 招标预告
                refreshRecyclerBase(mAdapterPre, list, isLoadMore, noMoreData);
                break;
        }
    }

    public <T> void refreshRecyclerBase(HomeOtherMemberAdapter adapter, List<T> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setNoMore(noMoreData);
        adapter.setType(TextUtils.isEmpty(mNo1) ? 0 : 1);
        closeRecyclerRefreshing();
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                adapter.setDatas(list);
            } else {
                adapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        switch (mCurTenderPos) {
            case 0: // 全部
                mBinding.chooseLayout.setVisibility(View.GONE);
                mBinding.popAddress.setVisibility(View.VISIBLE);
                break;
            case 1: // 招标公告
                mBinding.chooseLayout.setVisibility(View.VISIBLE);
                mBinding.popSort.setVisibility(View.VISIBLE);
                mBinding.popStatus.setVisibility(View.VISIBLE);
                break;
            case 2: // 直接竞价
                mBinding.chooseLayout.setVisibility(View.VISIBLE);
                mBinding.popSort.setVisibility(View.VISIBLE);
                mBinding.popMoney.setVisibility(View.VISIBLE);
                break;
            case 3: // 招标预告
                mBinding.chooseLayout.setVisibility(View.VISIBLE);
                mBinding.popSort.setVisibility(View.VISIBLE);
                mBinding.popMode.setVisibility(View.VISIBLE);
                break;
        }
        mBinding.otherType.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popStatus.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popMoney.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popMode.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popSort.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popAddress.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.otherType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getContext() == null) return;
                SparseArray<XChooseEntity> temData = new SparseArray<>();
                SparseIntArray temFilter = new SparseIntArray();
                for (Integer integer : mCateOther) {
                    if (integer != PickCateType.TYPE_2) {
                        temFilter.put(integer, mFilters.get(integer));
                        temData.put(integer, mData.get(integer));
                    }
                }
                new XPopup.Builder(getContext())
                        .atView(mBinding.surveyLayout)
                        .popupAnimation(PopupAnimation.NoAnimation)
                        .offsetY(2)
                        .asCustom(new TenderTypeOtherPopup(getContext(), mCateTitle,
                                temData, temFilter, new TenderTypeOtherPopup.IResult() {
                            @Override
                            public void onResult(CommonPopEntity entity, SparseArray<XChooseEntity> data, SparseIntArray filter) {
                                if (entity == null) return;
                                for (int i = 0; i < filter.size(); i++) {
                                    int key = filter.keyAt(i);
                                    mFilters.put(key, filter.get(key));
                                    mData.put(key, data.get(key));
                                }
                                mNo2 = entity.getNo();
                                if (TextUtils.isEmpty(mNo2)) {
                                    mBinding.otherType.refreshChoose(entity.getNo(), "分类", 0);
                                } else {
                                    mBinding.otherType.refreshChoose(entity.getNo(), entity.getTypeName(), 1);
                                }
                                loadData(false);
                            }
                        }))
                        .show();
            }
        });
        mBinding.popAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    sModel.getAddressModel(PickCateType.TYPE_8);
                } else {
                    showAddressPopup();
                }
            }
        });
        initAddressPopup();
    }


    /**
     * 更新综合排序
     */
    public void updateSortInfo(List<CommonPopEntity> data) {
        mBinding.popSort.setData(data);
        mBinding.popSort.showPop();
    }

    private void showAddressPopup() {
        mBinding.popLine.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(mNo8) || !TextUtils.isEmpty(mNo9)) {
            mBinding.popAddress.updateChooseTextStatus(-2, null);
        } else {
            mBinding.popAddress.updateChooseTextStatus(-1, mBinding.popAddress.getKeyName());
        }
        mAddressPop.showPopwindow0(mBinding.popLine);
    }

    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                mNo8 = "";
                mNo9 = "";
                mFilters.put(PickCateType.TYPE_8, mAddressPop.getProvincePosition());
                addMainEntity(PickCateType.TYPE_9, new ArrayList<>());
                mBinding.popAddress.updateChooseTextStatus(0, mBinding.popAddress.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    mNo8 = entity.getProvinceNo();
                    mFilters.put(PickCateType.TYPE_8, mAddressPop.getProvincePosition());
                    mBinding.popAddress.updateChooseTextStatus(1, entity.getProvinceName());
                    updateCityData(new CommonPopEntity(entity.getProvinceNo(), entity.getProvinceName()), mAddressPop.getProvincePosition(), false);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        mNo9 = entity.getCityNo();
                        mFilters.put(PickCateType.TYPE_9, mAddressPop.getmCityPosition());
                        mBinding.popAddress.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                loadData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mNo8) || !TextUtils.isEmpty(mNo8)) {
                mBinding.popAddress.updateChooseTextStatus(1, null);
            } else {
                mBinding.popAddress.updateChooseTextStatus(0, mBinding.popAddress.getKeyName());
            }
        });
    }

    @Override
    public void onLoadChooseData(String mKeyName) {
        if ("招标状态".equals(mKeyName)) {
            sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_3, "", false);
        } else if ("招标方式".equals(mKeyName)) {
            sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_4, "", false);
        } else if ("概算金额".equals(mKeyName)) {
            sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_6, "", false);
        } else if ("综合排序".equals(mKeyName)) {
            sModel.getSortData(mCurTenderPos);
        }
    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        if ("招标状态".equals(mKeyName)) {
            if (!TextUtils.equals(no, mNo3)) {
                mNo3 = no;
                mFilters.put(PickCateType.TYPE_3, position);
                loadData(false);
            }
        } else if ("招标方式".equals(mKeyName)) {
            if (!TextUtils.equals(no, mNo4)) {
                mNo4 = no;
                mFilters.put(PickCateType.TYPE_4, position);
                loadData(false);
            }
        } else if ("概算金额".equals(mKeyName)) {
            if (!TextUtils.equals(no, mNo6)) {
                mNo6 = no;
                mFilters.put(PickCateType.TYPE_6, position);
                loadData(false);
            }
        } else if ("综合排序".equals(mKeyName)) {
            if (!TextUtils.equals(no, mNoSort)) {
                mNoSort = no;
                loadData(false);
            }
        }
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    // 数据集
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    // 二级分类关联数据
    private List<Integer> mCateOther;

    private SparseArray<String> mNameArray;

    private void initChooseDialog() {
        mCateOther = new ArrayList<>();
        mCateOther.add(PickCateType.TYPE_2);
        mCateOther.add(PickCateType.TYPE_21);
        mCateOther.add(PickCateType.TYPE_22);
        mCateOther.add(PickCateType.TYPE_23);
        mCateOther.add(PickCateType.TYPE_24);
        mCateOther.add(PickCateType.TYPE_25);
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_1, "招标类型");
        for (Integer integer : mCateOther) {
            mNameArray.put(integer, "分类");
        }
        mNameArray.put(PickCateType.TYPE_3, "招标状态");
        mNameArray.put(PickCateType.TYPE_4, "招标方式");
        mNameArray.put(PickCateType.TYPE_5, "报名开始时间");
        mNameArray.put(PickCateType.TYPE_51, "报名截止时间");
        mNameArray.put(PickCateType.TYPE_6, "概算金额");
        mNameArray.put(PickCateType.TYPE_7, "发布时间");
        mNameArray.put(PickCateType.TYPE_8, "省份");
        mNameArray.put(PickCateType.TYPE_9, "市区");
        mNameArray.put(PickCateType.TYPE_10, "会员级别");
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    public void showLeftDialog(int type, List<CommonPopEntity> data) {
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    public void addMainEntity(int index, String name, List<CommonPopEntity> list) {
        if (!TextUtils.isEmpty(name)) {
            mNameArray.put(index, name);
        }
        if (mData.get(index) != null) {
            mData.get(index).setTypeName(mNameArray.get(index));
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        // 资质类型当前不需要联动
        switch (entity.getSort()) {
            case PickCateType.TYPE_1:
                loadTenderSecondType(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_2:
            case PickCateType.TYPE_21:
            case PickCateType.TYPE_22:
            case PickCateType.TYPE_23:
            case PickCateType.TYPE_24:
            case PickCateType.TYPE_25:
                loadTenderOtherType(entity.getSort(), entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_8:
                updateCityData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            default:
                break;
        }
    }

    // 更新二级数据
    private void loadTenderSecondType(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        int category = !TextUtils.isEmpty(entity.getNo()) ? Integer.parseInt(entity.getNo()) : 0;
        String[] cateTitle = CopyUtils.getCateTitle(pos, category);
        String name1 = cateTitle[0];
        String name2 = cateTitle[1];
        String name3 = cateTitle[2];
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_2, name1, new ArrayList<>());
            mChooseDialog.addEntity(PickCateType.TYPE_21, name2, new ArrayList<>());
            mChooseDialog.addEntity(PickCateType.TYPE_22, name3, new ArrayList<>());
            for (Integer integer : mCateOther) {
                mChooseDialog.addEntity(integer, new ArrayList<>());
            }
        } else {
            addMainEntity(PickCateType.TYPE_2, name1, new ArrayList<>());
            addMainEntity(PickCateType.TYPE_21, name2, new ArrayList<>());
            addMainEntity(PickCateType.TYPE_22, name3, new ArrayList<>());
            for (Integer integer : mCateOther) {
                addMainEntity(integer, new ArrayList<>());
            }
        }
        if (pos > 0) {
            sModel.loadTenderType(mCurTenderPos, PickCateType.TYPE_2, entity.getNo(), isShowLeftDialog);
        }
    }

    private void loadTenderOtherType(int sort, CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        ArrayList<CommonPopEntity> objects = new ArrayList<>();
        for (int i = 0; i < mCateOther.size(); i++) {
            Integer integer = mCateOther.get(i);
            if (integer > sort) {
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(integer, objects);
                } else {
                    addMainEntity(integer, objects);
                }
            }
        }
        if (pos > 0 && mCateOther.contains(sort + 1)) {
            int index = mCateOther.indexOf(sort) + 1;
            if (entity.getChildren() != null && entity.getChildren().size() > 0) {
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(mCateOther.get(index), entity.getChildren());
                } else {
                    addMainEntity(mCateOther.get(index), entity.getChildren());
                }
            } else {
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(mCateOther.get(index), objects);
                } else {
                    addMainEntity(mCateOther.get(index), objects);
                }
            }
        }
    }

    private void updateCityData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_9, new ArrayList<>());
        } else {
            addMainEntity(PickCateType.TYPE_9, new ArrayList<>());
        }
        if (pos > 0) {
            sModel.getAddressCityData(scrData, entity.getNo(), PickCateType.TYPE_9, isShowLeftDialog);
        }
    }

    private boolean isTabOneDialogRefresh;
    private boolean isTabTwoDialogRefresh;

    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        isTabOneDialogRefresh = true;
        isTabTwoDialogRefresh = true;
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            refreshItemValue(key, mFilters.get(key), true);
        }
        isTabOneDialogRefresh = false;
        loadData(false);
    }

    private void refreshItemValue(int key, int value, boolean isDialog) {
        XChooseEntity entity = mData.get(key);
        mFilters.put(key, value);
        String itemNo = entity.getItemNo(value);
        switch (key) {
            case PickCateType.TYPE_1:
                mNo1 = itemNo;
                int tabCount1 = mBinding.tabType1.getTabCount();
                if (isDialog && tabCount1 > 0) {
                    Objects.requireNonNull(mBinding.tabType1.getTabAt(value)).select();
                }
                break;
            case PickCateType.TYPE_2:
                mNo2 = itemNo;
                if (value > 0 && entity.getList() != null && entity.getList().size() > 0) {
                    mBinding.otherType.setVisibility(View.VISIBLE);
                } else {
                    mBinding.otherType.setVisibility(View.GONE);
                }
                int tabCount = mBinding.tabType2.getTabCount();
                if (isDialog && tabCount > 0) {
                    updateTenderTypes2(entity.getList(), value);
                }
                break;
            case PickCateType.TYPE_21:
            case PickCateType.TYPE_22:
            case PickCateType.TYPE_23:
            case PickCateType.TYPE_24:
            case PickCateType.TYPE_25:
                if (value > 0) {
                    mNo2 = itemNo;
                    mBinding.otherType.refreshChoose(mNo2, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_3: // 招标状态
                mNo3 = itemNo;
                mBinding.popStatus.refreshChoose(mNo3, entity.getItemName(value), value);
                break;
            case PickCateType.TYPE_4: // 招标方式
                mNo4 = itemNo;
                mBinding.popMode.refreshChoose(mNo4, entity.getItemName(value), value);
                break;
            case PickCateType.TYPE_5: // 报名开始时间
                mNo5 = itemNo;
                break;
            case PickCateType.TYPE_51: // 报名截至时间
                mNo51 = itemNo;
                break;
            case PickCateType.TYPE_6: // 概算金额
                mNo6 = itemNo;
                mBinding.popMoney.refreshChoose(mNo6, entity.getItemName(value), value);
                break;
            case PickCateType.TYPE_7: // 发布时间
                mNo7 = itemNo;
                break;
            case PickCateType.TYPE_8: // 省
                mNo8 = itemNo;
                mBinding.popAddress.refreshChoose(mNo8, entity.getItemName(value), value);
                mAddressPop.setDefPosition(value, 0);
                break;
            case PickCateType.TYPE_9: // 市
                mNo9 = itemNo;
                mAddressPop.setDefPosition(mFilters.get(PickCateType.TYPE_8), value);
                if (value > 0) {
                    mBinding.popAddress.refreshChoose(mNo9, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_10:
                member_level = entity.getItemId(value);
                break;
            default:
                break;
        }
    }

    @Override
    public void reset() {
        mFilters.clear();
        resetMainData();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();
    }

    private void resetMainData() {
        for (Integer integer : mCateOther) {
            addMainEntity(integer, new ArrayList<>());
        }
        addMainEntity(PickCateType.TYPE_9, new ArrayList<>());
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }


}
